#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QFile>
#include <QFileDialog>
#include <QEventLoop>
#include <QDebug>
#include "protocol.h"

#define BUF_SIZE 254 /**/

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 设置 左上角的名称
    this->setWindowTitle("cls uart tools V1.0.0");

    // 遍历能用的串口加到 界面串口的下拉框里
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        ui->comboBox->addItem(info.portName());
    }

    connect(&serialPort, &BaseSerialport::sendData, this, &MainWindow::receiveMsg);
    connect(&serialPort, &BaseSerialport::openResult, this,&MainWindow::trigLight);
    connect(this, &MainWindow::send, &serialPort, &BaseSerialport::send);
    connect(this, &MainWindow::close, &serialPort, &BaseSerialport::close);
    connect(this, &MainWindow::open, &serialPort, &BaseSerialport::open);

    serialPort.moveToThread(&serialThread);
    serialThread.start();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_key_off_clicked()
{
    ui->LED1->setStyleSheet("background-color:black");
    emit close();
}

void MainWindow::on_key_on_clicked()
{
    QSerialPort::BaudRate baudRate;
    QSerialPort::StopBits stopBits;
    QSerialPort::DataBits dataBits;
    QSerialPort::Parity dataParity;

    // 波特率
    if (ui->comboBox_2->currentText() == "9600")
    {
        baudRate = QSerialPort::Baud9600;
    }
    else if (ui->comboBox_2->currentText() == "115200")
    {
        baudRate = QSerialPort::Baud115200;
    }

    // 停止位
    if (ui->comboBox_3->currentText() == "1")
    {
        stopBits = QSerialPort::OneStop;
    }
    else if (ui->comboBox_3->currentText() == "1.5")
    {
        stopBits = QSerialPort::OneAndHalfStop;
    }
    else if (ui->comboBox_3->currentText() == "2")
    {
        stopBits = QSerialPort::TwoStop;
    }

    // 数据位
    if (ui->comboBox_4->currentText() == "5")
    {
        dataBits = QSerialPort::Data5;
    }
    else if (ui->comboBox_4->currentText() == "6")
    {
        dataBits = QSerialPort::Data6;
    }
    else if (ui->comboBox_4->currentText() == "7")
    {
        dataBits = QSerialPort::Data7;
    }
    else if (ui->comboBox_4->currentText() == "8")
    {
        dataBits = QSerialPort::Data8;
    }

    // 校验位
    if (ui->comboBox_5->currentText() == "None")
    {
        dataParity = QSerialPort::NoParity;
    }
    else if (ui->comboBox_5->currentText() == "Odd")
    {
        dataParity = QSerialPort::OddParity;
    }
    else if (ui->comboBox_5->currentText() == "Even")
    {
        dataParity = QSerialPort::EvenParity;
    }

    emit open(ui->comboBox->currentText(), baudRate, dataBits, dataParity, stopBits);
}

void MainWindow::receiveMsg(QByteArray msg){
    // 接收串口消息再这里
    ui->textBrowser->setText(QString::fromLocal8Bit(msg));
    qDebug() << msg.toHex();
}

void MainWindow::trigLight(bool isOpen){
    // 灯的颜色变红
    if(isOpen)
        ui->LED1->setStyleSheet("background-color:red");
}

void MainWindow::on_Send_Key_clicked()
{
    QByteArray tx_buf = ui->textEdit->toPlainText().toUtf8();

    emit send(tx_buf);
}

void MainWindow::on_OpenFileButton_clicked()
{
    // QEventLoop loop;
    // // QString path = QFileDialog::getOpenFileName(this, "open", "../", "HEX(*.hex);;BIN(*.bin)");
    // QString path = QFileDialog::getOpenFileName(this, "open", "../", "HEX(*.hex *.bin)");
    // // QString path = QFileDialog::getOpenFileName(this, "open", "../", "BIN(*.bin)");
    // if (!path.isEmpty())
    // {
    //     QFile file(path);
    //     // bool isOk = file.open(QIODevice::ReadOnly);
    //     // if (isOk)
    //     // {
    //     //     QByteArray array = file.readAll(); // 读取文本中全部文件
    //     // }
    //     if (file.open(QIODevice::ReadOnly))
    //     {
    //         char filebuf[BUF_SIZE] = {0};
    //         int real_read_size = 0;

    //         auto con1 = connect(&serialPort, &serialPort::sendMsg, this, [&](QByteArray msg) {

    //             if ((int) msg.at(0) == protocol::Fflag::start)
    //                 loop.quit();
    //         });
    //         send(protocol::writeFile(filebuf, real_read_size, protocol::Fflag::start));
    //         loop.exec();
    //         disconnect(con1);

    //         QDataStream stream(&file);

    //         auto con2 = connect(&serialPort, &serialPort::sendMsg, this, [&](QByteArray msg) {
    //             if (msg.at(0) == protocol::Fflag::ing)
    //                 loop.quit();
    //             else
    //                 send(protocol::writeFile(filebuf, real_read_size, protocol::Fflag::ing));
    //         });

    //         while (!stream.atEnd())
    //         {
    //             real_read_size = stream.readRawData(filebuf, sizeof(filebuf));
    //             send(protocol::writeFile(filebuf, real_read_size, protocol::Fflag::ing));
    //             loop.exec();
    //         }
    //         disconnect(con2);

    //         auto con3 = connect(&serialPort, &serialPort::sendMsg, this, [&](QByteArray msg) {
    //             if (msg.at(0) == protocol::Fflag::end)
    //                 loop.quit();
    //         });

    //         send(protocol::writeFile(filebuf, real_read_size, protocol::Fflag::end));
    //         loop.exec();
    //         disconnect(con3);
    //     }
    //     file.close();
    // }
}

